import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 25228
 * Date: 2024-09-17
 * Time: 21:02
 */
public class Test {
    public static void main(String[] args) {
        int[] array={1,5,8,0,33,64,32};
        //selectSort(array);
        heapSort(array);
        System.out.println(Arrays.toString(array));
    }
    public static void swap(int[] array, int i,int j){
        int tmp=array[i];
        array[i]=array[j];
        array[j]=tmp;
    }


    // 选择排序
    public static void selectSort(int[] array){
        for (int i = 0; i < array.length-1; i++) {
            int min=i;
            int j = i+1;
            for (; j < array.length; j++) {
                if(array[j]<array[min]){
                    min=j;
                }
            }
            swap(array,i,min);
        }
    }


    // 堆排序
    public static void heapSort(int[] array){
        createHeap(array);
        int end=array.length-1;
        while(end>0){
            swap(array,0,end);
            sift(array,0,end);
            end--;
        }
    }

    public static void createHeap(int[] array){
        for (int p = (array.length-2)/2; p >=0 ; p--) {
            sift(array,p,array.length);
        }
    }

    public static void sift(int[] array,int p,int len){
        int c=p*2+1;
        while (c<len){
            if(c+1<len && array[c]<array[c+1]){
                c++;
            }
            if(array[c]>array[p]){
                swap(array,c,p);
                p=c;
                c=p*2+1;
            }else {
                break;
            }
        }
    }
}
